const dayjs = require('dayjs');
/**
 * 样品管理MobX状态
 */
import { observable, action  } from '../../../miniprogram_npm/mobx-miniprogram/index';
import cloudHelper from '../../../helpers/cloudHelper.js';
import pageHelper from '../../../helpers/pageHelper.js';
import dateHelper from '../../../helpers/dateHelper.js';

// 样品管理状态存储
const sampleStore = observable({
  // 样品列表
  sampleList: [],
  
  // 当前选中的样品
  currentSample: null,
  
  // 样品详情
  sampleDetail: null,
  
  // 筛选条件
  filter: {
    search: '',  // 搜索关键词
    status: '',  // 状态筛选
    sort: 'time'  // 排序方式:time/view
  },
  
  // 分页数据
  pagination: {
    page: 1,
    size: 20,
    total: 0,
    hasMore: true
  },
  
  // 页面状态
  loading: false,
  
  // 权限状态
  canAdd: false,
  
  // 页面加载状态
  loading: {
    list: false,
    detail: false,
    submit: false
  },
  
  // 选项数据
  options: {
    statusOptions: [
      { label: '调试中', value: 1 },
      { label: '试产中', value: 2 },
      { label: '大货中', value: 3 }
    ],
    projectOptions: [],
    statusIndex: 0,
    projectIndex: -1
  },
  
  // 表单数据
  formData: {
    SAMPLE_CODE: '',
    SAMPLE_NAME: '',
    SAMPLE_VERSION: '',
    SAMPLE_CUSTOMER: '',
    SAMPLE_PROJECT_ID: '',
    SAMPLE_STATUS: 1, 
    SAMPLE_LOCATION: '',
    SAMPLE_MAKE_USER_ID: '',
    SAMPLE_NOTES: '',
    SAMPLE_ATTACHMENTS: []
  },
  
  // 调试模式
  debugMode: true,
  
  // 调试数据
  debugData: [{
    _id: 'debug_1',
    SAMPLE_CODE: 'DBG001',
    SAMPLE_NAME: '调试样品1',
    SAMPLE_VERSION: 'V1.0',
    SAMPLE_CUSTOMER: '测试客户',
    SAMPLE_STATUS: 1,
    statusDesc: '调试中',
    SAMPLE_LOCATION: '测试位置',
    engineerName: '测试工程师',
    createTime: '2024-01-01',
    SAMPLE_ATTACHMENTS: [
      '/projects/oa/images/home.jpg'
    ]
  }],
  
  // 设置搜索关键词
  setSearchKey: action(function(key) {
    this.filter.search = key;
  }),
  
  // 设置状态筛选
  setStatusFilter: action(function(status) {
    this.filter.status = status;
  }),
  
  // 设置排序方式
  setSort: action(function(sort) {
    this.filter.sort = sort;
  }),
  
  // 重置分页
  resetPagination: action(function() {
    this.pagination.page = 1;
    this.pagination.hasMore = true;
    this.sampleList = [];
  }),
  
  // 加载样品列表
  loadSampleList: action(async function() {
    if (this.loading || !this.pagination.hasMore) return;
    
    try {
      this.loading = true;
      
      const params = {
        search: this.filter.search,
        status: this.filter.status,
        sortType: this.filter.sort,
        page: this.pagination.page,
        size: this.pagination.size
      };
      
      const result = await cloudHelper.callCloudData('sample/list', params);
      
      if (result && result.list) {
        // 添加新数据到列表
        if (this.pagination.page === 1) {
          this.sampleList = result.list;
        } else {
          this.sampleList = this.sampleList.concat(result.list);
        }
        
        // 更新分页信息
        this.pagination.total = result.total || 0;
        this.pagination.hasMore = this.sampleList.length < this.pagination.total;
        this.pagination.page++;
      }
      
      this.loading = false;
      return result;
    } catch (error) {
      console.error('加载样品列表失败:', error);
      this.loading = false;
      throw error;
    }
  }),
  
  // 检查添加权限
  checkAddPermission: action(async function() {
    try {
      const result = await cloudHelper.callCloudData('sample/check_permission', {});
      this.canAdd = (result && result.can_add) ? true : false;
      return this.canAdd;
    } catch (error) {
      console.error('检查添加权限失败:', error);
      this.canAdd = false;
      return false;
    }
  }),
  
  // 加载样品详情
  loadSampleDetail: action(async function(id) {
    if (!id) return;
    
    this.loading.detail = true;
    
    try {
      let params = {
        id
      };
      
      let res = await cloudHelper.callCloudData('sample/detail', params);
      this.currentSample = res;
      this.sampleDetail = res;
    } catch (err) {
      console.error('加载样品详情失败:', err);
      
      if (this.debugMode) {
        this.currentSample = this.debugData[0];
        this.sampleDetail = this.debugData[0];
        pageHelper.showNoneToast('调试模式：加载模拟数据');
      }
    } finally {
      this.loading.detail = false;
    }
  }),
  
  // 处理图片加载错误
  handleImageError: action(function(index) {
    if (index < 0 || index >= this.sampleList.length) return;
    
    // 设置默认图片
    if (this.sampleList[index].SAMPLE_IMAGES && this.sampleList[index].SAMPLE_IMAGES.length > 0) {
      this.sampleList[index].SAMPLE_IMAGES[0] = '/projects/oa/images/default.png';
    }
  }),

  // 重置表单数据
  resetFormData: action(function() {
    this.formData = {
      SAMPLE_CODE: '',
      SAMPLE_NAME: '',
      SAMPLE_VERSION: '',
      SAMPLE_CUSTOMER: '',
      SAMPLE_PROJECT_ID: '',
      SAMPLE_STATUS: 1,
      SAMPLE_LOCATION: '',
      SAMPLE_MAKE_USER_ID: '',
      SAMPLE_NOTES: '',
      SAMPLE_ATTACHMENTS: []
    };
    
    this.options.statusIndex = 0;
    this.options.projectIndex = -1;
  }),
  
  // 设置表单字段值
  setFormField: action(function(field, value) {
    this.formData[field] = value;
  }),
  
  // 设置状态索引 
  setStatusIndex: action(function(index) {
    this.options.statusIndex = index;
    this.formData.SAMPLE_STATUS = this.options.statusOptions[index].value;
  }),
  
  // 设置项目索引
  setProjectIndex: action(function(index) {
    this.options.projectIndex = index;
    if (index >= 0 && this.options.projectOptions[index]) {
      this.formData.SAMPLE_PROJECT_ID = this.options.projectOptions[index].value;
    } else {
      this.formData.SAMPLE_PROJECT_ID = '';
    }
  }),
  
  // 加载选项数据
  loadOptions: action(async function() {
    try {
      if (this.debugMode) {
        this.options.projectOptions = [
          { label: '无', value: '' },
          { label: '项目A', value: 'proj_001' },
          { label: '项目B', value: 'proj_002' }
        ];
        return;
      }
      
      // 加载项目选项
      let projectRes = await cloudHelper.callCloudData('sample/project');
      console.log('服务端返回的项目选项:', projectRes);
      
      // 添加"无"选项
      let projectOptions = [{ label: '无', value: '' }];
      if (projectRes && Array.isArray(projectRes) && projectRes.length > 0) {
        projectOptions = projectOptions.concat(projectRes);
      }
      
      this.options.projectOptions = projectOptions;
      this.options.projectIndex = 0;  // 默认选中"无"
      
      console.log('设置项目选项成功:', projectOptions);
    } catch (err) {
      console.error('加载选项失败:', err);
      if (this.debugMode) {
        this.options.projectOptions = [
          { label: '无', value: '' },
          { label: '项目A', value: 'proj_001' },
          { label: '项目B', value: 'proj_002' }
        ];
      }
    }
  }),
  
  // 添加图片附件
  addAttachments: action(async function(tempFiles) {
    try {
      let SAMPLE_ATTACHMENTS = this.formData.SAMPLE_ATTACHMENTS || [];
      
      for (let i = 0; i < tempFiles.length; i++) {
        let file = tempFiles[i];
        let cloudPath = `samples/${dayjs().valueOf()}_${i}.jpg`;
        
        try {
          let uploadRes = await cloudHelper.transTempPic(file.tempFilePath, cloudPath);
          console.log('上传结果:', uploadRes);
          
          // 处理不同格式的返回值
          let fileUrl = '';
          if (uploadRes.cloudURLs && uploadRes.cloudURLs[0]) {
            fileUrl = uploadRes.cloudURLs[0];
          } else if (uploadRes.fileID) {
            fileUrl = uploadRes.fileID;
          } else if (typeof uploadRes === 'string') {
            fileUrl = uploadRes;
          }
          
          if (fileUrl) {
            SAMPLE_ATTACHMENTS.push(fileUrl);
          }
        } catch (err) {
          console.error('上传单张图片失败:', err);
          pageHelper.showModal('部分图片上传失败，请重试');
        }
      }
      
      this.formData.SAMPLE_ATTACHMENTS = SAMPLE_ATTACHMENTS;
      return SAMPLE_ATTACHMENTS;
    } catch (err) {
      console.error('添加图片附件失败:', err);
      throw err;
    }
  }),
  
  // 删除图片附件
  removeAttachment: action(function(index) {
    let SAMPLE_ATTACHMENTS = this.formData.SAMPLE_ATTACHMENTS;
    SAMPLE_ATTACHMENTS.splice(index, 1);
    this.formData.SAMPLE_ATTACHMENTS = SAMPLE_ATTACHMENTS;
  }),
  
  // 提交表单 - 添加样品
  submitSampleAdd: action(async function() {
    this.loading.submit = true;
    
    try {
      if (this.debugMode) {
        console.log('调试模式：模拟提交', this.formData);
        await new Promise(resolve => setTimeout(resolve, 1000));
        this.loading.submit = false;
        return { id: 'debug_new_id' };
      }
      
      let params = { ...this.formData };
      let result = await cloudHelper.callCloudData('sample/insert', params);
      this.loading.submit = false;
      return result;
    } catch (err) {
      console.error('添加样品失败:', err);
      this.loading.submit = false;
      throw err;
    }
  }),
  
  // 加载编辑数据
  loadEditData: action(async function(id) {
    try {
      if (this.debugMode) {
        this.formData = { ...this.debugData[0] };
        
        // 设置项目和状态索引
        const statusIndex = this.options.statusOptions.findIndex(
          item => item.value === this.formData.SAMPLE_STATUS
        );
        this.options.statusIndex = statusIndex > -1 ? statusIndex : 0;
        
        const projectIndex = this.options.projectOptions.findIndex(
          item => item.value === this.formData.SAMPLE_PROJECT_ID
        );
        this.options.projectIndex = projectIndex > -1 ? projectIndex : 0;
        
        return { success: true };
      }
      
      const detail = await cloudHelper.callCloudData('sample/detail', { id });
      
      if (detail) {
        this.formData = { ...detail };
        
        // 设置项目和状态索引
        const statusIndex = this.options.statusOptions.findIndex(
          item => item.value === detail.SAMPLE_STATUS
        );
        this.options.statusIndex = statusIndex > -1 ? statusIndex : 0;
        
        const projectIndex = this.options.projectOptions.findIndex(
          item => item.value === detail.SAMPLE_PROJECT_ID
        );
        this.options.projectIndex = projectIndex > -1 ? projectIndex : 0;
        
        return { success: true };
      }
      
      return { success: false };
    } catch (err) {
      console.error('加载编辑数据失败:', err);
      throw err;
    }
  }),
  
  // 提交表单 - 编辑样品
  submitSampleEdit: action(async function(id) {
    this.loading.submit = true;
    
    try {
      if (this.debugMode) {
        console.log('调试模式：模拟编辑提交', this.formData);
        await new Promise(resolve => setTimeout(resolve, 1000));
        this.loading.submit = false;
        return { success: true };
      }
      
      let params = { ...this.formData, id };
      let result = await cloudHelper.callCloudData('sample/edit', params);
      this.loading.submit = false;
      return result;
    } catch (err) {
      console.error('编辑样品失败:', err);
      this.loading.submit = false;
      throw err;
    }
  })
});

export {
  sampleStore
}; 